package cn.iocoder.yudao.module.handguard.tool.http;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class TestRedirectExample {
    public static void main(String[] args) {
//        String url = "https://cq.ke.com/xiaoqu/rs";
//
//        try {
//            String redirectedUrl = getRedirectedUrl(url);
//            System.out.println("重定向后的地址：" + redirectedUrl);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

//        String url = "https://captcha.lianjia.com/captcha/pre-validate?sceneId=sec-hip&token=icRJVsouEVFBTiYVcYbjR8puYPr7H9V8&challenger=2764&callback=__jp1";
//        String result = getCaptchaImage(url);
//        System.out.println(result);
    }

    private static String getCaptchaImage(String url) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static String getRedirectedUrl(String url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setInstanceFollowRedirects(false); // 禁止自动处理重定向
        connection.setRequestMethod("GET");
        
        int statusCode = connection.getResponseCode();
        if (statusCode >= 300 && statusCode < 400) {
            String redirectedUrl = connection.getHeaderField("Location");
            return redirectedUrl;
        }
        return "0"; // 如果没有重定向，返回原始链接
    }
}